package com.zaoke.web.common;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import com.zaoke.web.component.utils.SpringUtil;

@Service
public class LocaleFilter implements Filter{

	/**
	 * 为什么@Autowired失效了
	 */
	//@Autowired(required = true) 
	private static CookieLocaleResolver localeResolver;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		localeResolver=(CookieLocaleResolver) SpringUtil.getBean("localeResolver");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		Locale locale= localeResolver.resolveLocale(httpRequest);
		if(locale==null){
			locale=Locale.ENGLISH;
		}else if(Locale.ENGLISH.getLanguage().equals(locale.getLanguage())){
			locale=Locale.ENGLISH;
		}else if(Locale.CHINESE.getLanguage().equals(locale.getLanguage())){
			locale=Locale.CHINESE;
		}else{
			locale=Locale.ENGLISH;
		}
		localeResolver.setLocale (httpRequest, httpResponse, locale);
		localeResolver.setCookieMaxAge(Integer.MAX_VALUE);//不可少，设置cookie失效时间的
		System.out.println(locale);
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
